from django.conf import settings
from fdfs_client.client import Fdfs_client

from home.models import House, HouseImage
from tenement_project.libs.qiniuyun.qiniu_storage import storage


def up_avatar(avatar, request):
    client = Fdfs_client('tenement_project/utils/fastdfs/client.conf')
    old_image_id = request.user.avatar
    try:
        client.delete_file(old_image_id.name)  # 删除老图片

    except Exception as e:
        ret = client.upload_by_buffer(avatar)  # 新图片
        new_image_id = ret['Remote file_id']
        request.user.avatar = new_image_id
        request.user.save()


def up_house_image(house_data, house_id):
    client = Fdfs_client('tenement_project/utils/fastdfs/client.conf')
    try:
        house = House.objects.get(id=house_id)
    except Exception as e:
        return True
    old_image_id = house.index_image_url
    try:
        client.delete_file(old_image_id)  # 删除老图片
    except Exception as e:
        ret = client.upload_by_buffer(house_data)  # 新图片
        new_image_id = ret['Remote file_id']

        house.index_image_url = settings.BASE_URL + new_image_id
        house.save()


def qiliuyun_avatar(avatar_data, request):
    result = storage(avatar_data.read())
    request.user.avatar = result
    request.user.save()


def qiliuyun_house_image(house_data, house_id):
    try:
        house = House.objects.get(id=house_id)
    except Exception as e:
        return True
    result = storage(house_data.read())
    if house.index_image_url:
        HouseImage.objects.create(url=settings.QNY_URL + result, house_id=house_id)
        return settings.QNY_URL + result
    else:
        house.index_image_url = settings.QNY_URL + result
        house.save()
        return settings.QNY_URL + result